<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>编辑商品</title>
  <link href="../../static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../../static/vendor/bootstrap-icons/bootstrap-icons.min.css" rel="stylesheet">
  <link href="../../static/css/vui365.min.css" rel="stylesheet">
</head>

<body>
  <div id="app">
    <form class="form-main form-horizontal" style="height:100vh" method="POST" ref="editForm">
      <div class="form-body container-fluid p-3"
        style="height:calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
        <div class="row skeleton" v-for="(col, idx) of getColumns('form')" :key="idx">
          <label class="col-sm-2 col-form-label">{{ col.text }}</label>
          <div class="col-sm-9" v-if="col.component == 'email'">
            <div class="input-group input-group-sm">
              <span class="input-group-text">EMAIL</span>
              <input class="form-control form-control-sm" :name="col.name" type="text" placeholder="电子邮箱" />
            </div>
          </div>
          <div class="col-sm-9" v-else-if="col.component == 'radio'">
            <radio-input :name="col.name" :value="dataOfMain.data[col.name]"
              :data-source="dataOfMain[col.name + '_data']">
            </radio-input>
          </div>
          <div class="col-sm-9" v-else-if="col.component == 'select'">
            <select-input :name="col.name" :value="dataOfMain.data[col.name]"
              :data-source="dataOfMain[col.name + '_data']" value-field="value" text-field="text"
              @change="onChangeSelect($event)"></select-input>
          </div>
          <div class="col-sm-9" v-else-if="col.component == 'imguploader'">
            <upload-input :name="col.name" :value="dataOfMain.data[col.name]" param="{imgwidth:150,imgheight:150}"
              data-file-accept="image/*" data-file-multiplex="true"></upload-input>
          </div>
          <div class="col-sm-9" v-else>
            <input class="form-control form-control-sm" :name="col.name" :value="dataOfMain.data[col.name]"
              :type="col.component" :placeholder="col.placeholder||col.text" required />
          </div>
        </div>
        <!-- /.form-body -->
      </div>
      <div class="form-footer border-top pt-2 w-100 text-end">
        <button type="button" class="btn btn-secondary" @click.prevent="onCancelHandle()">取消</button>
        <cd-button class="btn btn-primary mx-2" @click="onSubmitHandle()">保存</cd-button>
    </form>
  </div>

  <script src="../../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../../static/vendor/vue/vue.global.prod.min.js"></script>
  <script>
    // 全局配置
    this.vui365 = this.parent.vui365;

    // API接口配置
    const UrlCfg = {
      show: '/api/admin/ec-goods/{id}', // GET
      store: '/api/admin/ec-goods', // POST
      update: '/api/admin/ec-goods/{id}', // PUT
      getBrandData: '/api/admin/ec-brand',
    }
    /**
     * 管理员组件
     * @description 管理员组件
     */
    const App = {
      // data 配置
      data() {
        return {
          id: 0,
          dataOfMain: {
            data: {},
            status_data: []
          },
        };
      },
      // methods 配置
      methods: {
        // 初始化页面数据
        initData() {
          this.loadFormData();
        },
        // 初始化页面视图
        initView() {
          // 移除骨架屏
          document.querySelectorAll('.skeleton').forEach(el => {
            el.classList.remove("skeleton");
          })
          // 自动生成标题
          document.querySelector('[name="category_id"],[name="brand_id"]').addEventListener('change', function (evt) {
            let elCategory=document.querySelector('[name="category_id"]');
            let elBrand=document.querySelector('[name="brand_id"]');
            let elName=document.querySelector('[name="goods_name"]');
            let data=[
              elCategory.options[elCategory.selectedIndex].text.replaceAll('|----',''),
              elBrand.options[elBrand.selectedIndex].text,
              elName.value,
            ];
            document.querySelector('[name="seo_title"]').value = data.join(' ');
          })
          document.querySelector('[name="goods_name"]').addEventListener('input', function (evt) {
            let elCategory=document.querySelector('[name="category_id"]');
            let elBrand=document.querySelector('[name="brand_id"]');
            let elName=document.querySelector('[name="goods_name"]');
            let data=[
              elCategory.options[elCategory.selectedIndex].text.replaceAll('|----',''),
              elBrand.options[elBrand.selectedIndex].text,
              elName.value,
            ];
            document.querySelector('[name="seo_title"]').value = data.join(' ');
          })
        },
        // 加载表单数据
        async loadFormData() {
          vui365.globalApp.showLoading();
          const msgInfo = await vui365.stdAxios(UrlCfg.show.replace('{id}', this.id), {}, 'GET');
          vui365.globalApp.hideLoading();
          // console.log("[加载表单数据] msgInfo=", this.id, msgInfo);
          if (msgInfo.status == 0) {
            alert(msgInfo.message);
            return;
          }
          this.dataOfMain = msgInfo.data;
          // console.log("[加载表单数据] data=", this.dataOfMain);
        },
        // 处理表单提交事件
        async onSubmitHandle() {
          let elForm = document.querySelector("form");
          // 表单原生校验方法
          if (!elForm.checkValidity()) {
            elForm.reportValidity();
            return;
          }
          let formData = new FormData(elForm);
          if (formData.length == 0) {
            vui365.BsDialog.alert('表单无效');
            return;
          }
          let data = {}
          formData.forEach((v, k) => {
            data[k] = v;
          });
          let msgInfo = {}
          if (this.id > 0) {
            msgInfo = await vui365.stdAxios(UrlCfg.update.replace('{id}', this.id), data, 'PUT');
          } else {
            msgInfo = await vui365.stdAxios(UrlCfg.store, data, 'POST');
          }
          console.log("[提交表单] msgInfo=", msgInfo, formData);
          if (msgInfo.status == 0) {
            if (typeof msgInfo.message == "object") {
              let messageArr = [];
              for (let k in msgInfo.message) {
                msgInfo.message[k].forEach((text) => {
                  messageArr.push(text);
                });
              }
              msgInfo.message = messageArr.join("<br />");
            }
            vui365.BsDialog.alert(msgInfo.message);
            console.log('显示错误');
            return;
          }
          vui365.globalApp.closeFormDialog();
          vui365.globalApp.refreshDataTable()
        },
        // 处理表单取消事件
        onCancelHandle() {
          vui365.globalApp.closeFormDialog();
        },
        // 选择分类，刷新品牌数据
        async onChangeSelect($event) {
          let elSelect = $event.target;
          if (elSelect.name == 'category_id') {
            vui365.globalApp.showLoading();
            const msgInfo = await vui365.stdAxios(UrlCfg.getBrandData, { _mode: 'dict', category_id: elSelect.value }, 'GET');
            vui365.globalApp.hideLoading();
            if (msgInfo.status == 0) {
              vui365.BsDialog.alert(msgInfo.message);
              return;
            }
            this.dataOfMain.brand_id_data = msgInfo.data;
          }
        },
        // 获取数剧列的配置内容
        getColumns(isForm = false) {
          let columns = [
            { name: "id", text: "ID", component: "text", view: "r" },
            {
              name: "goods_name",
              text: "商品名称",
              component: "text",
              view: "cru",
              placeholder: '商品名称（例如：葵花籽油6.18L）'
            },
            {
              name: "category_id",
              text: "分类",
              component: "select",
              view: "cru",
            },
            {
              name: "brand_id",
              text: "品牌",
              component: "select",
              view: "cru",
            },
            {
              name: "seo_title",
              text: "商品标题",
              component: "text",
              view: "cru",
              placeholder: '商品标题（分类 + 品牌 + 品名）'
            },
            {
              name: "icon",
              text: "图标",
              component: "imguploader",
              view: "cru",
            },
            {
              name: "price",
              text: "价格",
              component: "number",
              view: "cru",
            },
            {
              name: "quantity",
              text: "库存量",
              component: "number",
              view: "cru",
            },
            {
              name: "created_at",
              text: "创建时间",
              component: "text",
              view: "r",
            },
            {
              name: "status",
              text: "状态",
              component: "radio",
              view: "cru",
            },
          ];
          let data = [], isEdit = this.id > 0;
          for (let col of columns) {
            if (isForm) {
              if (isEdit && col.view.indexOf("u") > -1) {
                data.push(col);
              } else if (col.view.indexOf("c") > -1) {
                data.push(col);
              }
              continue;
            }
            if (col.view.indexOf("r") > -1) {
              data.push(col);
            }
          }
          return data;
        },
      },
      // created 生命周期方法
      created() {
        this.id = vui365.EsUtils.getQueryString("id", 0, window.location.search);
        this.initData();
      },
      // mounted 生命周期方法
      mounted() {
        this.initView();
      },
    };

    // 创建应用实例
    const app = Vue.createApp(App);
    //  注册组件
    app.component("UploadInput", vui365.getComponentOfUploadInput())
    app.component("SelectInput", vui365.getComponentOfSelectInput())
    app.component("CheckboxInput", vui365.getComponentOfCheckboxInput())
    app.component("RadioInput", vui365.getComponentOfRadioInput())
    app.component("CdButton", vui365.getComponentOfCdButton())
    // 加载根元素
    app.mount('#app');
  </script>

</body>

</html>